package com.wuwangfu.transfor;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * @Author jcshen
 * @Date 2023-02-22
 * @PackageName:com.wuwangfu.transfor
 * @ClassName: FilterTransf
 * @Description:
 * @Version 1.0.0
 *
 * https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/overview/#filter
 */
public class FilterTransf {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<Integer> nums = env.fromElements(1, 2, 3, 4, 5, 6, 7, 8, 9);

        SingleOutputStreamOperator<Integer> filtered = nums.filter(new FilterFunction<Integer>() {
            /**
             * 返回 true的数据
             * 过滤掉false的数
             *
             * @param value
             * @return
             * @throws Exception
             */
            @Override
            public boolean filter(Integer value) throws Exception {
                return value % 2 == 0;
            }
        });
        //filtered.print();

        SingleOutputStreamOperator<Integer> transform = nums
                .transform("my-filter", TypeInformation.of(Integer.class), new MyFilter());

        transform.print();

        env.execute();
    }

    private static class MyFilter extends AbstractStreamOperator<Integer> implements OneInputStreamOperator<Integer,Integer> {
        @Override
        public void processElement(StreamRecord<Integer> element) throws Exception {
            Integer value = element.getValue();
            if (value % 2 == 0){
                output.collect(element);
            }
        }
    }
}
